﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace MassIntellect.WorkIt
{
    public interface IWarningHandlerKeeper
    {
        bool WarningHandle(IPipe sender, string mnemo, object[] args, string desc);
    }

    public class Warning : IWarningHandlerKeeper, ISerialize
    {
        /// <summary>
        /// Разрешить выполнение в случае неизвестного предупреждения
        /// </summary>
        [Serialize(SerializeAs.Attribute)]
        public bool IsPermitUnknown { get; set; }

        /// <summary>
        /// Игнорировать регистр мнемокода
        /// </summary>
        [Serialize(SerializeAs.Attribute)]
        public bool IsIgnoreCase
        {
            get { return _IsIgnoreCase; }
            set
            {
                if (value != _IsIgnoreCase)
                {
                    permits = new Dictionary<string, bool>(permits, value
                                                                     ? StringComparer.CurrentCultureIgnoreCase
                                                                     : StringComparer.CurrentCulture);
                    _IsIgnoreCase = value;
                }
            }
        }
        private bool _IsIgnoreCase;

        private Dictionary<string, bool> permits = new Dictionary<string, bool>();

        #region IWarningHandler Members

        public bool WarningHandle(IPipe sender, string mnemo, object[] args, string desc)
        {
            return permits.GetOrDefault(mnemo, IsPermitUnknown);
        }

        #endregion

        #region ISerialize Members

        public void SetUp(XElement xe)
        {
            XAttribute xa;
            bool? b;
            foreach (var item in xe.Elements("add"))
                if ((xa = item.Attribute("mnemo")) != null)
                    permits.AddOrSetValue(xa.Value, (b = (bool?)item).HasValue ? b.Value : IsPermitUnknown);

            foreach (var item in xe.Elements("remove"))
                if ((xa = item.Attribute("mnemo")) != null)
                    permits.Remove(xa.Value);
        }

        public XElement Serialize()
        {
            XElement xe = XmlSerializeProvider.SerializeOnlyPropertyAndType(this, false);
            xe.Add(permits
                .Select(s => new XElement("add",
                    new XAttribute("name", s.Key),
                    new XAttribute("value", s.Value))));
            return xe;
        }

        #endregion
    }
}
